package com.ht.api.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

import jakarta.annotation.Resource;

/**
 * 拦截器配置
 * @author asq
 * @createTime 2024年12月22日 16:41:10
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
	@Resource
	private HandlerInterceptor authHandler;
	@Resource
	private HandlerInterceptor timeHandler;
	@Resource
	private HandlerInterceptor loginUserHandler;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		//登陆及权限验证
		registry.addInterceptor(authHandler).addPathPatterns("/**")
			.excludePathPatterns(excludePathPatterns().toArray(new String[0]));;

		//访问耗时打印
		registry.addInterceptor(timeHandler).addPathPatterns("/**");
		
		//注入登陆用户
		registry.addInterceptor(loginUserHandler).addPathPatterns("/**");
	}

	/**
	 * 不拦截的路径
	 * @return
	 */
	private List<String> excludePathPatterns() {
		List<String> patterns = new ArrayList<>();
		patterns.add("/websocket");
		return patterns;
	}

	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig());
		return new CorsFilter(source);
	}
	
	@Bean
	public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
	    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
	    SimpleModule simpleModule = new SimpleModule();
	    simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
	    objectMapper.registerModule(simpleModule);
	    return objectMapper;
	}

	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
		corsConfiguration.addAllowedHeader("*"); // 2允许任何头
		corsConfiguration.addAllowedMethod("*"); // 3允许任何方法（post、get等） 
		return corsConfiguration;
	}
}
